import React, { Fragment } from 'react';
import { get } from '@/utils/localStorage';
import { Navigate, useLocation } from 'react-router-dom';
import Login from '@/views/Login/Login';
import Register from '@/views/Register/Register';
import LoginCallback from '@/views/Login/components/LoginCallback/LoginCallback';

interface AuthRouterProps {
  children: React.ReactNode;
}

const AuthRouter: React.FunctionComponent<AuthRouterProps> = ({ children }) => {

  // 拿到url信息
  const location = useLocation();

  /**
   * @description 权限控制的回调函数
   * */
  const auth = () => {
    const loginInfo = get();
    if (loginInfo) {
      if (location.pathname === '/login') {
        return <Navigate to="/"></Navigate>;
      } else {
        return children;
      }
    } else {
      if (location.pathname === '/login') {
        return <Login></Login>;
      } else if (location.pathname === '/register') {
        return <Register></Register>;
      } else if (location.pathname === '/login/callback') {
        return <LoginCallback></LoginCallback>;
      } else {
        return <Login></Login>;
      }
    }
  };

  return (
    <Fragment>
      {auth()}
    </Fragment>
  );

};

export default AuthRouter;